package com.gopay.common.util;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

public class CommonUtils {

	/**
	 * 从一个字符串中安全地得到数字 如果没有数字则返回0
	 * 
	 * @param input
	 * @return
	 */
	public static int getInt(Object input) {
		
		if(input == null) {
            return 0;
        }
		
		Pattern p = Pattern.compile("-?\\d+");
		
		Matcher m = p.matcher(String.valueOf(input));
		
		if (m.find()) {
			return Integer.parseInt(m.group());
		} else {
			return 0;
		}
		
	}
	
	public static String getRemoteRealIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		
		return ip;
	}
	
	/**
	 * 从一个字符串中安全地得到数字 如果没有数字则返回0
	 * 
	 * @param input
	 * @return
	 */
	public static long getLong(Object input) {
		
		if(input == null) {
            return 0;
        }
		
		Pattern p = Pattern.compile("-?\\d+");
		
		Matcher m = p.matcher(String.valueOf(input));
		
		if (m.find()) {
			return Long.parseLong(m.group());
		} else {
			return 0;
		}
		
	}

	/**
	 * 从一个字符串中得到a-zA-Z的字符
	 * */
	public static String getCharacter(String input) {
		if (input == null || input.trim() == "") {
			return null;
		}

		Pattern p = Pattern.compile("[a-zA-Z]+");
		Matcher m = p.matcher(input);
		if (m.find()) {
			return m.group();
		} else {
			return null;
		}
	}
	
	/**
	 * 从一个字符串中得到汉字
	 * */
	public static String getChinese(String input) {
		if (input == null || input.trim() == "") {
			return null;
		}

		Pattern p = Pattern.compile("[\u4e00-\u9fa5]+");
		Matcher m = p.matcher(input);
		if (m.find()) {
			return m.group();
		} else {
			return null;
		}
	}
	
	/**
	 * 默认的日期转化格式 2007-6-26 16:56:30
	 * 
	 * DataFormat:yyyy-MM-dd HH:mm:ss
	 * 
	 * @param date
	 * @return
	 */
	public static String formatDate(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(date);
	}

	/**
	 * 自定义的日期转化格式
	 * 
	 * DataFormat:yyyy-MM-dd kk:mm:ss
	 * 
	 * @param date
	 * @param format
	 * @return
	 */
	public static String formatDate(Date date, String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(date);
	}	
	
	/**
	 * 自定义的日期转化格式 按符号分隔（symbol）
	 * 
	 * 传入格式yyyy-MM-dd
	 * 按照symbol分隔 例如2011.12.26
	 * @param date
	 * @param format
	 * @return
	 */
	public static String formatDate(Date date, String format,String symbol) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		String dateStr = sdf.format(date);
		return dateStr.replaceAll("-", ".");
	}
	
	/**
	 * DataFormat:yyyy-MM-dd kk:mm:ss
	 * */
	public static Date parseDate(String date,String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		try {
			return sdf.parse(date);
		} catch (ParseException e) {
			return new Date();
		}
	}
	
//	/**
//	 * MD5(UUID)
//	 * */
//	public static String getRandomToken(){
//		return EncodeUtils.getMD5(UUID.randomUUID().toString());
//	}
	
	public static String getRandomString(int length) { 
        StringBuffer buffer = new StringBuffer("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"); 
        StringBuffer sb = new StringBuffer(); 
        Random r = new Random(); 
        int range = buffer.length(); 
        for (int i = 0; i < length; i ++) { 
            sb.append(buffer.charAt(r.nextInt(range))); 
        }
        return sb.toString(); 
    }
	
	/**
	 * 判断是否是数字或字母(长度>=1).
	 *
	 * @param value
	 *            String
	 * @return ture or false
	 */
	public static boolean isNumOrLett(String value) {
		return validateFormat(value, "^[0-9]*$");
	}
	
	/**
	 * 验证格式.
	 *
	 * @param formValue
	 *            需要验证的字符串
	 * @param formatString
	 *            格式名
	 * @return boolean 1：合法，0：不合法
	 */
	public static boolean validateFormat(String formValue, String formatString) {
		boolean match = true;
		if(formatString == null || formatString.trim().length() == 0) {
			return match;
		}
		try {
			match = Pattern.matches(formatString, formValue);
		} catch (PatternSyntaxException e) {
			e.printStackTrace();
		}
		// add check character '
		if((formValue.indexOf("'")) >= 0) {
			match = false;
		}
		return match;
	}
	
	/**
	 * 根据文件路径得到文件的扩展名，如：.doc,.docx,.txt
	 */
	public static String getExtFromFilePath(String filePath){
		if(StringUtils.isBlank(filePath)){
			return "";
		}		
		return filePath.substring(filePath.lastIndexOf("."));
	}
	
	public static String getUUID(){
		return UUID.randomUUID().toString();
	}

	public static String md5(String message) {
		try {
			return DigestUtils.md5Hex(message.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String sha(String message){
		try {
			return DigestUtils.shaHex(message.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static boolean checkMobile(String mobile){
		if(StringUtils.isBlank(mobile)){
			return false;
		}
		
//		String regex = "^(13[0-9]|14[0-9]|15[0-9]|18[0-9])\\d{8}$";
		//增加17段
		String regex = "^1\\d{10}$";
		
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(mobile);
		
		return m.matches();
	}
	
	/**
	 * 检查手机验证码是否正确
	 * 验证码必须是6位长度的数字
	 * */
	public static boolean checkVerificationCode(String code){
		if (StringUtils.isBlank(code)) {
			return false;
		}
		code = StringUtils.trim(code);
		if (code.length() != 6) {
			return false;
		}
		
		try {
			return !Pattern.matches(code, "^[0-9]+$");
		} catch (PatternSyntaxException e) {
			e.printStackTrace();
		}
	
		return false;
	}
	
	/**
	 * 检查手机验证码是否正确
	 * 验证码必须是6位长度的数字
	 * */
	public static boolean checkUserId(String userId){
		if (StringUtils.isBlank(userId)) {
			return false;
		}
		
		userId = StringUtils.trim(userId);
		if (userId.length() != 10) {
			return false;
		}
		
		try {
			return !Pattern.matches(userId, "^[0-9]+$");
		} catch (PatternSyntaxException e) {
			e.printStackTrace();
		}
	
		return false;
	}
	
	public static void main(String[] args) {
		System.out.println(checkVerificationCode(""));
	}
}
